<template>  
  <div><el-dialog  v-model="dialog.isdialog">
    
    <el-card>
      <h3>{{dialog.title}}</h3>
      <p>{{dialog.content}}</p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.isdialog = false">取 消</el-button>
        <el-button type="primary" @click="dialog.isdialog = false">确 定</el-button>
      </div>
    </el-card>

</el-dialog> </div> 
      <el-container>  
    
        <el-header>编辑</el-header>  
        <el-main>  
          <el-form :model="post" ref="postForm" @submit.native.prevent="submitPost" enctype="multipart/form-data">  
            <el-form-item label="标题" prop="title">  
              <el-input v-model="post.title"></el-input>   
            </el-form-item>  
            <el-upload
            action="/api/upload/file1"
            :on-success="handleUploadSuccess"
            :before-upload="beforeImageUpload"
            :auto-upload="true"
            class="upload-demo"
          >
            <el-button slot="trigger">点击上传</el-button>
            <template #tip>
              仅支持jpg/png格式，大小不超过2MB。
            </template>
          </el-upload>
            <el-form-item label="内容" prop="content">  
              <el-input
              type="textarea"
              :rows="20" 
              resize="both" 
              v-model="post.content"
              @input="updateMarkdownPreview"
             
            ></el-input>            </el-form-item>  
            <!-- 上传封面图片 -->  
            <el-form-item>  
              <el-upload   
                class="avatar-uploader"  
               
                :show-file-list="false"  
               
                :before-upload="beforeAvatarUpload">  
                <img v-if="post.coverImage" :src="post.coverImage" class="avatar">  
                <i v-else class="el-icon-plus avatar-uploader-icon">封面</i>  
              </el-upload>  
            </el-form-item>  
            <el-form-item>  
              <el-button type="primary" native-type="submit">Submit</el-button>  
            </el-form-item>  
          </el-form>  
        </el-main>  
      </el-container>  
      <el-container>  
        <el-header>MD效果：</el-header>  
        <el-main>  
            <h3>{{post.title}}</h3>
          <div id="markdownPreview" v-html="convertToHtml(post.content)"></div>  
        </el-main>  
      </el-container>  
   
  </template>  
    
  <script setup lang="ts">  
import MarkdownIt from 'markdown-it'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'

import { useUserStore } from '@/stores/user';
import axios from 'axios'
import { useRouter } from 'vue-router';
const router = useRouter();
const md = new MarkdownIt()
const dialog = ref({
  title: '',
  content: '',
  isdialog: false
})

const user = useUserStore();
var my_id: number = user.loginstatus ? user.userInfo.id : -1;

function handleClick() {
  if (my_id==-1) {
    // 如果用户未登录，跳转到登录页面
    router.push({ name: 'login' });
  } else {
    // 处理需要用户登录的操作
    console.log('执行需要登录的操作');
  }
}

//添加未登录提示
if(my_id==-1){
  dialog.value.title = '提示'
  dialog.value.content = '请先登录'
  dialog.value.isdialog = true
  link()
}
function link() {
  if (my_id === -1&&dialog.value.content === '请先登录') {
    window.location.href = "./login";
  } 
 
}
    const post = ref({
        
          title: '',  
          content: '',  
          coverImage: ''  
        },) 


     // 处理图片上传成功后的回调
     const handleUploadSuccess = (response: any) => {
  if (response && response.path) {
    // 构建Markdown图片语法并追加到内容中
    const markdownImage = `\n![图片描述](${response.path})\n`;
    post.value.content += markdownImage;
  } else {
    ElMessage.error('图片上传成功，但未返回预期的URL');
  }
};

const beforeImageUpload = (rawFile: File) => {
  // const isJPGorPNG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png';
  // const isLt2M = rawFile.size / 1024 / 1024 < 4;

  // if (!isJPGorPNG) {
  //   ElMessage.error('只能上传 JPG 或 PNG 格式的图片！');
  //   return false;
  // }
  // if (!isLt2M) {
  //   ElMessage.error('图片大小不能超过 4MB！');
  //   return false;
  // }
  rawFile = rawFile // 减少报错
  handleClick()
  return true;
};
        
 const convertToHtml = (content: string) => {
    return md.render(content)
}    

   function   submitPost() { 
    var formData = new FormData();
    formData.append('id', my_id.toString());
    formData.append('title', post.value.title);
    formData.append('content', post.value.content);
    formData.append('coverImage', post.value.coverImage);
    
        // 处理表单提交逻辑  
        axios.post('/api/writer/create', formData).then(res => {  
          
          // 提交成功后的逻辑  
          dialog.value.title = '提示'
          dialog.value.content = '提交成功'
          dialog.value.isdialog = true
          //跳转到文章详情页
          window.location.href = "./article/" + res.data.id;
          return res.data
        }).catch(() => {  
          // 提交失败后的逻辑  
          
          dialog.value.title = '提示'
          dialog.value.content = '提交失败'
          dialog.value.isdialog = true
          
          
        })
      } 
      function updateMarkdownPreview() {  
        // 更新 Markdown 预览逻辑  
      } 
     
      function beforeAvatarUpload(file:File) {  
        const isJPG = file.type === 'image/jpeg';  
        const isLt2M = file.size / 1024 / 1024 < 2;  
    
        if (!isJPG) {  
            return
        }  
        if (!isLt2M) {  
          return
        }  
        if (isJPG && isLt2M) {  
          console.log(file);
          post.value.coverImage= put("image",file);
          
          if(post.value.coverImage==="error"){
            dialog.value.title = '提示'
            dialog.value.content = '上传失败'
            dialog.value.isdialog = true
          }

}

         
     
        }
       
         function   put (filetype:string,file:File) {

const user = useUserStore();
var my_id: number = user.loginstatus ? user.userInfo.id : -1;
const fileurl = ref("")
axios.post(`/api/upload/`+my_id,{
    filetype : filetype,
    file: file

},{  headers: {
        
'Content-Type': 'multipart/form-data'
             }}).then((res) => {
              console.log(res.data.path );
              fileurl.value = res.data.path;

}).catch((err) => {
  console.log(err);
  
fileurl.value =  "error";
});
return fileurl
};
      
    

  </script>  
    
<style>  
  .avatar-uploader .el-upload {  
    border: 1px dashed #d9d9d9;  
    border-radius: 6px;  
    cursor: pointer;  
    position: relative;  
    width: 100px;  
    height: 100px;  
  }  
  .avatar-uploader .el-upload:hover {  
    border-color: #409EFF;  
  }  
  .avatar-uploader-icon {  
    font-size: 28px;  
    color: #8c939d;  
    width: 100px;  
    height: 100px;  
    line-height: 100px;  
    text-align: center;  
  }  
  .avatar {  
    width: 100px;  
    height: 100px;  
    display: block;  
  }  
 
.resizable-textarea {
  /* 允许文本区域水平和垂直方向上拉伸 */
  resize: both;
  overflow: auto; /* 保证文本溢出时出现滚动条 */
  min-width: 300px; /* 例如，设置最小宽度为300px */
  min-height: 100px; /* 设置最小高度为100px */
}
</style>